package com.xu.chuang.show.network;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by coder on 2015/11/12.
 * http request.
 * @author MagicRain
 */
public class HttpUtil {
    public static String get(String path)  {
        System.out.println("GET:  "+ path);
        try {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();// 利用HttpURLConnection对象,我们可以从网络中获取网页数据.
            conn.setConnectTimeout(5 * 1000);   // 单位是毫秒，设置超时时间为5秒
            conn.setRequestMethod("GET");       // HttpURLConnection是通过HTTP协议请求path路径的，所以需要设置请求方式,可以不设置，因为默认为GET
            InputStream is = conn.getInputStream(); // 获取输入流
            return readStream(is);   // 把输入流转换成字符数组
        }catch (Exception e){
            e.printStackTrace();
        }
        return "";
    }

    private static String readStream(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is), 16*1024); //强制缓存大小为16KB，一般Java类默认为8KB
        StringBuilder sb = new StringBuilder();
        String line ;
        try {
            while ((line = reader.readLine()) != null) {  //处理换行符
                sb.append(line ).append("\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return sb.toString();
    }


    /**
     * 发送HttpPost请求
     *
     * @param strURL
     *            服务地址
     * @param params
     *            json字符串,例如: "{ \"id\":\"12345\" }" ;其中属性名必须带双引号<br/>
     */
    public static void post(String strURL, String params) {
        System.out.println("POST:  "+ strURL);
        System.out.println(params);
        try {
            URL url = new URL(strURL);// 创建连接
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setConnectTimeout(5 * 1000);
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod("POST"); // 设置请求方式
            connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
            connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
            connection.connect();
            OutputStreamWriter out = new OutputStreamWriter(
                    connection.getOutputStream(), "UTF-8"); // utf-8编码
            out.append(params);
            out.flush();
            out.close();
            // 读取响应
            int length =  connection.getContentLength();// 获取长度
            InputStream is = connection.getInputStream();

            if (length != -1) {
                byte[] data = new byte[length];
                byte[] temp = new byte[512];
                int readLen ;
                int destPos = 0;
                while ((readLen = is.read(temp)) > 0) {
                    System.arraycopy(temp, 0, data, destPos, readLen);
                    destPos += readLen;
                }
                String result = new String(data, "UTF-8"); // utf-8编码
                System.out.println(result);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
